import threading

import handle
import loginRequest
from getXybCode import app, code_queue
from concurrent.futures import ThreadPoolExecutor
import time

# 创建一个线程池，最大工作线程数设为5
executor = ThreadPoolExecutor(max_workers=5)


def process_codes():
    while True:
        # 每次从队列中取出最多10个元素进行处理
        batch = []
        with app.app_context():  # 确保Flask上下文
            while code_queue and len(batch) < 10:
                code = code_queue.popleft()
                batch.append(code)

        # 将批量任务提交到线程池
        if batch:
            # print(f"Processing {len(batch)} codes...")
            for code in batch:
                executor.submit(handle.processByCode, code)

        time.sleep(1)  # 控制处理频率


if __name__ == '__main__':
    # 启动处理线程池
    processing_thread = threading.Thread(target=process_codes, daemon=True)
    processing_thread.start()

    # 启动Flask应用
    app.run(host='0.0.0.0', port=12345, debug=True)